---------------------------------------------------------------
-- @Description：         handle_gate
---------------------------------------------------------------
local skynet = require "skynet"
local gateserver = require "service_socket_gateserver"
local log = require "sky_log"

local watchdog
local connection = {}	-- fd -> connection : { fd , client, agent , ip, mode }
local forwarding = {}	-- agent -> connection


skynet.register_protocol {
	name = "client",
	id = skynet.PTYPE_CLIENT,
}

local handler = {}

function handler.initialization(source)
	watchdog = source
	log.info("service_gate handler.initialization!")
end

function handler.connect(fd, conn)
	connection[fd] = conn
	log.info("gate connected! connection=", connection)
end

function handler.message(fd, msg, sz)
	local c = connection[fd]
	local agent = c.agent
	if agent then
		skynet.redirect(agent, c.client, "client", fd, msg, sz)
	else
		skynet.send(watchdog, "lua", "socket", "data", fd, skynet.tostring(msg, sz))
		skynet.trash(msg, sz)
	end
end

local function unforward(c)
	if c.agent then
		forwarding[c.agent] = nil
		c.agent = nil
		c.client = nil
	end
end

local function close_fd(fd)
	local c = connection[fd]
	if c then
		unforward(c)
		connection[fd] = nil
	end
end

function handler.disconnect(fd)
	close_fd(fd)
	skynet.send(watchdog, "lua", "socket", "close", fd)
end

function handler.error(fd, msg)
	close_fd(fd)
	skynet.send(watchdog, "lua", "socket", "error", fd, msg)
end

function handler.warning(fd, size)
	skynet.send(watchdog, "lua", "socket", "warning", fd, size)
end

--============================= CMD =============================--
local CMD = {}

function CMD.forward(source, fd)
	local c = assert(connection[fd])
	unforward(c)
	c.client = fd or 0
	c.agent = source
	forwarding[c.agent] = c

	log.info("finish forwarding! ", forwarding)
	return gateserver.openclient(fd)
	--return true	
end

function CMD.kick(source, fd)
	gateserver.closeclient(fd)
end

function handler.command(cmd, source, ...)
	local f = assert(CMD[cmd])
	return f(source, ...)
end

gateserver.start(handler)
